package net.hzlj.platform.enterprise.activity;

import android.Manifest;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

import com.tencent.bugly.beta.Beta;

import net.hzlj.platform.enterprise.BootApp;
import net.hzlj.platform.enterprise.beans.UserBean;
import net.hzlj.platform.enterprise.beans.resp.RespBaseBean;
import net.hzlj.platform.enterprise.common.Constant;
import net.hzlj.platform.enterprise.config.HttpConfig;
import net.hzlj.platform.enterprise.helper.ToastHelper;
import net.hzlj.platform.enterprise.receiver.DeviceReceiver;
import net.hzlj.platform.enterprise.task.HttpRequestApi;
import net.hzlj.platform.enterprise.task.Task;
import net.hzlj.platform.enterprise.utils.AppPreferencesUtils;
import net.hzlj.platform.enterprise.utils.PreferencesUtils;
import net.hzlj.platform.enterprise.utils.StringUtils;
import net.hzlj.platform.enterprise.widght.TitleBar;
import net.hzlj.rl.zhangjiajie.R;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Description: 登录
 * @Author: Jason Zhang
 * @Date: 2016-8-26 15:39:51
 */
public class LoginActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {

    private static final String TAG = LoginActivity.class.getSimpleName();
    public static final String KEY_LOGIN_FROM = "key_login_from";

    @BindView(R.id.title_bar)
    TitleBar mTitleBar;
    @BindView(R.id.login_account)
    EditText mAccountEditText;
    @BindView(R.id.login_password)
    EditText mPasswordEditText;
    @BindView(R.id.login_remind_password)
    CheckBox mRemindPasswordCheckBox;
    @BindView(R.id.login_login)
    Button mLoginButton;

    private MyHandler<LoginActivity> mHandler;

    private boolean mIsHasInit = false;
    private String mAccount, mPassWord;
    private boolean mFromChangeAccount = false;

    public static LoginActivity LOGIN_ACTIVITY;

    @Override
    protected void setRootView() {
        super.setRootView();
        setContentView(R.layout.activity_login);
        LOGIN_ACTIVITY = this;
    }

    @Override
    protected void initTitleBar() {
        super.initTitleBar();
        mHandler = new MyHandler<LoginActivity>(this);
        mTitleBar.bindActivity(this);
        mFromChangeAccount = getIntent().getBooleanExtra(KEY_LOGIN_FROM,false);
        if (mFromChangeAccount){
            mTitleBar.RefreshTitleBar(TitleBar.Style.BACK);
            mTitleBar.setDisplayName(getString(R.string.title_login));
        }
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        mRemindPasswordCheckBox.setOnCheckedChangeListener(this);

    }

    @Override
    protected void initData() {
        super.initData();
//        mIsRemindPassword = AppPreferencesUtils.getBoolean(this, PreferencesUtils.KEY_REMIND_PASSWORD, true);
//        mRemindPasswordCheckBox.setChecked(mIsRemindPassword);
    }

    private void initPermission(){
        //检查权限
        //Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CALL_PHONE,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.RECORD_AUDIO,Manifest.permission.CAMERA})
        if (!selfPermissionGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE) ||
                !selfPermissionGranted(Manifest.permission.READ_EXTERNAL_STORAGE) ||
                !selfPermissionGranted(Manifest.permission.CALL_PHONE) ||
                !selfPermissionGranted(Manifest.permission.ACCESS_FINE_LOCATION) ||
                !selfPermissionGranted(Manifest.permission.ACCESS_COARSE_LOCATION) ||
                !selfPermissionGranted(Manifest.permission.RECORD_AUDIO) ||
                !selfPermissionGranted(Manifest.permission.CAMERA) ) {
            requestCameraPermission(new PermissionHandler() {
                @Override
                public void onGranted() {
                    Log.i(TAG,"onGranted");
                    if (mIsHasInit){
                        return;
                    }
                    checkLoginStatus();
                }

                @Override
                public void onDenied() {
                    super.onDenied();
                    Log.i(TAG,"onDenied");
                    ToastHelper.newInstance().show(LoginActivity.this, "部分权限没有授权，无法进入程序");
                    LoginActivity.this.finish();
                }
            });
        }else {
            if (mIsHasInit){
                return;
            }
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mIsHasInit = true;
                }
            });
            checkLoginStatus();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        DevicePolicyManager mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        ComponentName mDeviceComponentName = new ComponentName(this,
                DeviceReceiver.class);
        boolean flag = AppPreferencesUtils.getBoolean(BootApp.getAppContext(),PreferencesUtils.KEY_ALLOW_UNINSTALLATION, Constant.Socket.DEFAULT_ALLOW_UNINSTALL);
        Log.i(TAG,"onResume flag:" + flag);
        if (!flag && (mDPM.isAdminActive(mDeviceComponentName) == false)){
            Intent intentAdmin = new Intent(this,
                    DeviceAuthorizeActivity.class);
            intentAdmin.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            startActivity(intentAdmin);
        }else {
            initPermission();
        }
    }

    private void checkLoginStatus(){
        if (BootApp.netIsConnect(this)) {
            if (BootApp.getInstance().isLogin() && !mFromChangeAccount) {
                startActivity(new Intent(LoginActivity.this,HomeActivity.class));
                finish();
            } else {
                UserBean userBean = AppPreferencesUtils.getObject(this, PreferencesUtils.KEY_USER_INFO, UserBean.class);
                if (userBean != null && StringUtils.isNotEmpty(userBean.getIdentityNO())) {
                    mAccountEditText.setText(userBean.getIdentityNO());
                }
                if (BootApp.getInstance().isNeedUpdate()){
                    Beta.checkUpgrade();
                }
            }
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//        mIsRemindPassword = isChecked;
//        AppPreferencesUtils.putBoolean(this, PreferencesUtils.KEY_REMIND_PASSWORD, mIsRemindPassword);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LOGIN_ACTIVITY = null;
    }

    @OnClick(R.id.login_login)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_login:
                if (BootApp.getInstance().netIsConnect(this)) {
                    mLoadingDialog.show("登录中...", false);
                    mAccount = mAccountEditText.getText().toString();
                    mPassWord = mPasswordEditText.getText().toString();
                    HttpRequestApi.login(mAccount, mPassWord, this, this);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onTaskResult(Task task) {
        super.onTaskResult(task);
        if (task.type == HttpConfig.Type.LOGIN) {
            if (mLoadingDialog != null) {
                mLoadingDialog.dismiss();
            }
            ToastHelper.newInstance().show(this, task.rspDesc);
            if (task.isSuccess) {
                RespBaseBean<UserBean> respBaseBean = task.resData;
                if (respBaseBean.isSuccess()) {
                    UserBean userBean = respBaseBean.getValues().get(0);
                    AppPreferencesUtils.putObject(LoginActivity.this, PreferencesUtils.KEY_USER_INFO, userBean);
                    AppPreferencesUtils.putString(LoginActivity.this, PreferencesUtils.KEY_USER_ACCOUNT, mAccount);
                    startActivity(new Intent(LoginActivity.this,HomeActivity.class));
                    finish();
                }
            }
        }
    }

    @Override
    void handleMessage(BaseActivity activity, Message msg) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK
//                && event.getAction() == KeyEvent.ACTION_DOWN) {
//            AppManager.getAppManager().AppExit(LoginActivity.this);
//        }
        return super.onKeyDown(keyCode, event);
    }

}
